package com.rjpacket.supernews.app.fragments;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.rjpacket.supernews.app.Constants;
import com.rjpacket.supernews.app.FunnyNewsDetailActivity;
import com.rjpacket.supernews.app.NewsDetailActivity;
import com.rjpacket.supernews.app.R;
import com.rjpacket.supernews.app.adapter.FunnyNewsAdapter;
import com.rjpacket.supernews.app.models.News;
import com.rjpacket.supernews.app.models.NewsDetail;
import com.rjpacket.supernews.app.task.FunnyNewsDetailTask;
import com.rjpacket.supernews.app.task.FunnyNewsListTask;
import com.rjpacket.supernews.app.tasks.DetailTaskCallOnBack;
import com.rjpacket.supernews.app.tasks.TaskCallOnBack;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */

/**
 * 娱乐新闻的列表
 */
public class FunnyFragment extends Fragment implements PullToRefreshBase.OnRefreshListener2, AdapterView.OnItemClickListener, TaskCallOnBack, DetailTaskCallOnBack {

    private PullToRefreshListView refresh;
    private int headerViewsCount;
    private FunnyNewsAdapter adapter;
    private LinkedList<News> data;
    private String url;
    private View toastView;

    public FunnyFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View ret = inflater.inflate(R.layout.mz_fragment_funny, container, false);
        toastView = inflater.inflate(R.layout.my_toast_layout, null);

        //获得刷新控件
        refresh = (PullToRefreshListView) ret.findViewById(R.id.funny_pull_to_refresh_list_view);
        //设置两边都能刷新
        refresh.setMode(PullToRefreshBase.Mode.BOTH);

        //绑定监听器
        refresh.setOnRefreshListener(this);
        Resources res = getResources();
        Drawable drawable = res.getDrawable(R.drawable.light_loading_0);

        // 设置加载图标
        refresh.setLoadingDrawable(drawable);
        // 设置加载中的标题
        refresh.setRefreshingLabel("下拉可以刷新");
        // 设置“松开”提醒
        refresh.setReleaseLabel("松开即可刷新");

        //获得ListView
        ListView listView = refresh.getRefreshableView();
        //设置分割线
        listView.setDividerHeight(0);
        headerViewsCount = listView.getHeaderViewsCount();

        data = new LinkedList<News>();

        //设置Adapter
        adapter = new FunnyNewsAdapter(getActivity(), data);

        url = Constants.YULE_LIST_URL;

        listView.setAdapter(adapter);
        //设置点击事件
        listView.setOnItemClickListener(this);

        //获得列表
        FunnyNewsListTask task = new FunnyNewsListTask(this);
        task.execute(url);

        return ret;
    }

    /////////////////////////////////////
    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        FunnyNewsListTask task = new FunnyNewsListTask(this);
        task.execute(url);

        //加载完后  Toast提示,加载的内容
        Toast toast = new Toast(getActivity());
        toast.setView(toastView);
        toast.show();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        Toast.makeText(getActivity(), "上拉", Toast.LENGTH_SHORT).show();
    }
    ////////////////////////////////////

    //TODO 点击进入详情
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        //TODO 推荐页面的listView item点击事件,跳转
        Intent intent = new Intent(getActivity(), FunnyNewsDetailActivity.class);
        News news = data.get(position - headerViewsCount);
        intent.putExtra("news", news.getNewsDetail());
        startActivity(intent);

    }

    @Override
    public void callOnBack(Object object) {
        refresh.onRefreshComplete();
        if (object != null && object instanceof JSONObject) {
            //////////解析出返回数据的stime，sequence
            JSONObject result = (JSONObject) object;
            try {
                int status = result.getInt("status");
                if (status == 1) {

                    News news = new News();
                    news.parseJSON(result);
                    List<News> newsList = news.getList();

                    for (int i = 0; i < newsList.size(); i++) {
                        News item = newsList.get(i);
                        String nid = item.getNid();
                        //不同item的不同接口网址
                        String detailUrl = Constants.YULE_ITEM_URL + nid;

                        FunnyNewsDetailTask task = new FunnyNewsDetailTask(this);
                        task.execute(detailUrl, i + "");
                    }

                    data.addAll(0, newsList);
                    adapter.notifyDataSetChanged();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            //TODO 请检查网络
            Toast.makeText(getActivity(), "请检查网络", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void callBack(Object object, String position) {
        if (object != null && object instanceof JSONObject) {
            JSONObject json = (JSONObject) object;
            NewsDetail detail = new NewsDetail();
            detail.parseJSON(json);
            News news = data.get(Integer.parseInt(position));
            news.setNewsDetail(detail);
        }
    }
}
